﻿'
' DKP for DotNetNuke® - http://dkpdnn.codeplex.com
' Copyright (c) 2008
' by Casey Lengacher ( http://dkpdnn.codeplex.com )
'
' DotNetNuke®, DNN®, and the DotNetNuke logo are trademarks of DotNetNuke Corporation.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in
' all copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
'

Imports System.Xml
Imports DotNetNuke.Common.Utilities

Namespace DotNetNuke.Modules.tss_DKP

    Partial Public Class tss_ucItems

        Inherits Entities.Modules.PortalModuleBase

#Region "Private Variables"

        Private Enum PageState As Integer
            NotSet = -1
            View = 0
            Add = 1
            SingleUpdate = 2
            MultiUpdate = 3
        End Enum

#End Region

#Region "Private Properties"

        Private Property vsPageSize() As Integer
            Get
                If ViewState("tss_ItemPageSize") Is Nothing Then
                    If (Request.Cookies.Get("tss_ItemPageSize") Is Nothing) Then
                        Return ddlPageSize.Items(0).Value
                    Else
                        Return CInt(Request.Cookies.Get("tss_ItemPageSize").Value)
                    End If
                Else
                    Return CInt(ViewState("tss_ItemPageSize"))
                End If
            End Get
            Set(ByVal Value As Integer)
                ViewState("tss_ItemPageSize") = Value
                Response.Cookies("tss_ItemPageSize").Expires = DateTime.Now.AddYears(10)
                Response.Cookies("tss_ItemPageSize").Value = Value
            End Set
        End Property

        Private Property vsSortExpression() As String
            Get
                If ViewState("tss_ItemSortExpression") Is Nothing Then
                    If (Request.Cookies.Get("tss_ItemSortExpression") Is Nothing) Then
                        Return "ItemName"
                    Else
                        Return CStr(Request.Cookies.Get("tss_ItemSortExpression").Value)
                    End If
                Else
                    Return CStr(ViewState("tss_ItemSortExpression"))
                End If
            End Get
            Set(ByVal Value As String)
                ViewState("tss_ItemSortExpression") = Value
                Response.Cookies("tss_ItemSortExpression").Expires = DateTime.Now.AddYears(10)
                Response.Cookies("tss_ItemSortExpression").Value = Value
            End Set
        End Property

        Private Property vsSortDirection() As String
            Get
                If ViewState("tss_ItemSortDirection") Is Nothing Then
                    If (Request.Cookies.Get("tss_ItemSortDirection") Is Nothing) Then
                        Return "ASC"
                    Else
                        Return CStr(Request.Cookies.Get("tss_ItemSortDirection").Value)
                    End If
                Else
                    Return CStr(ViewState("tss_ItemSortDirection"))
                End If
            End Get
            Set(ByVal Value As String)
                ViewState("tss_ItemSortDirection") = Value
                Response.Cookies("tss_ItemSortDirection").Expires = DateTime.Now.AddYears(10)
                Response.Cookies("tss_ItemSortDirection").Value = Value
            End Set
        End Property

        Private Property vsCurrentPage() As Integer
            Get
                If ViewState("tss_ItemCurrentPage") Is Nothing Then
                    Return 1
                Else
                    Return CInt(ViewState("tss_ItemCurrentPage"))
                End If
            End Get
            Set(ByVal Value As Integer)
                ViewState("tss_ItemCurrentPage") = Value
            End Set
        End Property

        Private Property vsTotalPages() As Integer
            Get
                If ViewState("tss_ItemTotalPages") Is Nothing Then
                    Return 1
                Else
                    Return CInt(ViewState("tss_ItemTotalPages"))
                End If
            End Get
            Set(ByVal Value As Integer)
                ViewState("tss_ItemTotalPages") = Value
            End Set
        End Property

        Private Property vsPageState() As PageState
            Get
                If ViewState("tss_ItemPageState") Is Nothing Then
                    Return PageState.NotSet
                Else
                    Return CStr(ViewState("tss_ItemPageState"))
                End If
            End Get
            Set(ByVal Value As PageState)
                ViewState("tss_ItemPageState") = Value
            End Set
        End Property

#End Region

#Region "Private Methods"

        Private Sub BindPage()

            Dim tss_DKP As New tss_DataController
            Dim intRowsAffected As Integer
            Dim intPageNumber As Integer = vsCurrentPage
            Dim dblPagesAffected As Double = 1

            ddlPageSize.SelectedValue = ddlPageSize.Items.FindByText(vsPageSize).Value

            grdItems.PageSize = vsPageSize

            For Each currentColumn As DataGridColumn In grdItems.Columns
                currentColumn.HeaderText = currentColumn.HeaderText.Substring(0, _
                    IIf(currentColumn.HeaderText.IndexOf(" <img") > 0, currentColumn.HeaderText.IndexOf(" <img"), currentColumn.HeaderText.Length))
                If (currentColumn.SortExpression = vsSortExpression) Then
                    If (vsSortDirection = "ASC") Then
                        currentColumn.HeaderText = currentColumn.HeaderText _
                            + " <img src='/DesktopModules/tss_DKP/Images/grid_icon_uparrow.png' border=0 height=10 width=10>"
                    Else
                        currentColumn.HeaderText = currentColumn.HeaderText _
                            + " <img src='/DesktopModules/tss_DKP/Images/grid_icon_downarrow.png' border=0 height=10 width=10>"
                    End If
                End If
            Next

            grdItems.DataSource = tss_DKP.tss_GetItemsByPage(CInt(Settings("BoardID")), intPageNumber, grdItems.PageSize, vsSortExpression, vsSortDirection, intRowsAffected)
            grdItems.DataBind()

            If (grdItems.Items.Count = 0) And (intPageNumber > 1) Then
                intPageNumber = intPageNumber - 1
                vsCurrentPage = intPageNumber.ToString()
                grdItems.DataSource = tss_DKP.tss_GetItemsByPage(CInt(Settings("BoardID")), intPageNumber, grdItems.PageSize, vsSortExpression, vsSortDirection, intRowsAffected)
                grdItems.DataBind()
            End If

            dblPagesAffected = System.Math.Ceiling(intRowsAffected / grdItems.PageSize)
            If (dblPagesAffected < 1) Then
                dblPagesAffected = 1
            End If
            vsTotalPages = dblPagesAffected.ToString()
            lblCurrentPage.Text = vsCurrentPage
            lblTotalPages.Text = vsTotalPages

            If (intPageNumber = 1) Then
                lnkPreviousPage.Enabled = False

                If (dblPagesAffected > 1) Then
                    lnkNextPage.Enabled = True
                    lnkLastPage.Enabled = True
                Else
                    lnkNextPage.Enabled = False
                    lnkLastPage.Enabled = False
                End If
            Else
                lnkPreviousPage.Enabled = True

                If (intPageNumber = dblPagesAffected) Then
                    lnkNextPage.Enabled = False
                    lnkLastPage.Enabled = False
                Else
                    lnkNextPage.Enabled = True
                    lnkLastPage.Enabled = True
                End If
            End If

            If (DotNetNuke.Security.PortalSecurity.IsInRoles(Me.ModuleConfiguration.AuthorizedEditRoles)) And Not (UserId = -1) Then
                pnlEditPanel.Visible = True
                grdItems.Columns(0).Visible = True
            Else
                pnlEditPanel.Visible = False
                grdItems.Columns(0).Visible = False
            End If

        End Sub

        Private Sub ManagePageState(ByVal PageState As PageState)

            vsPageState = PageState

            If (PageState = PageState.View) Then
                grdItems.Enabled = True
                BindPage()
            Else
                grdItems.Enabled = False
            End If

            If (PageState = PageState.View) Then
                pnlEditPanelForm.Visible = False
            Else
                pnlEditPanelForm.Visible = True
            End If

            txtItemName.Text = Null.NullString
            txtItemValue.Text = Null.NullString
            txtItemPercent.Text = Null.NullString
            txtItemWowHeadID.Text = Null.NullString

            lblWarning.Text = Null.NullString

            If (PageState = PageState.Add) Or (PageState = PageState.SingleUpdate) Then

                pnlItemName.Visible = True
                pnlItemWowHeadID.Visible = True

                txtItemName.Focus()

            ElseIf (PageState = PageState.MultiUpdate) Then

                pnlItemName.Visible = False
                pnlItemWowHeadID.Visible = False

                txtItemValue.Focus()

            End If

        End Sub

#End Region

#Region "Private Event Handlers"

        Private Sub ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles grdItems.ItemDataBound

            If (e.Item.ItemType.Equals(ListItemType.Item)) Or (e.Item.ItemType.Equals(ListItemType.AlternatingItem)) Then

                Dim lblItemID As Label = e.Item.FindControl("lblItemID")
                Dim lnkItemWowHeadID As HyperLink = e.Item.FindControl("lnkItemWowHeadID")
                Dim lblItemName As Label = e.Item.FindControl("lblItemName")
                Dim lblItemValue As Label = e.Item.FindControl("lblItemValue")
                Dim lblItemPercent As Label = e.Item.FindControl("lblItemPercent")

                Dim objItem As tss_ItemInfo = e.Item.DataItem

                lblItemID.Text = objItem.ItemID.ToString()
                lblItemID.Visible = False

                If (objItem.ItemWowHeadID.Length = 0) Then
                    lnkItemWowHeadID.ImageUrl = "/DesktopModules/tss_DKP/Images/grid_icon_blank.png"
                    lnkItemWowHeadID.Enabled = False
                Else
                    lnkItemWowHeadID.ImageUrl = "/DesktopModules/tss_DKP/Images/grid_icon_wowhead.png"
                    lnkItemWowHeadID.NavigateUrl = "http://www.wowhead.com/?item=" + objItem.ItemWowHeadID
                    lnkItemWowHeadID.Target = "_new"
                    lnkItemWowHeadID.Enabled = True
                    lnkItemWowHeadID.ToolTip = "View WowHead"
                End If

                lblItemName.Text = objItem.ItemName
                lblItemValue.Text = objItem.ItemValue
                lblItemPercent.Text = objItem.ItemPercent

            End If

        End Sub

        Private Sub ItemCreated(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles grdItems.ItemCreated

            If (e.Item.ItemType.Equals(ListItemType.Header)) Then

                For Each currentCell As TableCell In e.Item.Cells
                    currentCell.Attributes.Add("class", "dkpdnn_GridHeader" + grdItems.Columns(e.Item.Cells.GetCellIndex(currentCell)).FooterText)
                Next

            ElseIf (e.Item.ItemType.Equals(ListItemType.Item)) Then

                e.Item.Attributes.Add("class", "dkpdnn_GridItem")
                e.Item.Attributes.Add("onmouseover", "className='dkpdnn_GridItemMouseOver';")
                e.Item.Attributes.Add("onmouseout", "className='dkpdnn_GridItem';")

                For Each currentCell As TableCell In e.Item.Cells
                    currentCell.Attributes.Add("class", "dkpdnn_GridItem" + grdItems.Columns(e.Item.Cells.GetCellIndex(currentCell)).FooterText)
                Next

            ElseIf (e.Item.ItemType.Equals(ListItemType.AlternatingItem)) Then

                e.Item.Attributes.Add("class", "dkpdnn_GridAltItem")
                e.Item.Attributes.Add("onmouseover", "className='dkpdnn_GridAltItemMouseOver';")
                e.Item.Attributes.Add("onmouseout", "className='dkpdnn_GridAltItem';")

                For Each currentCell As TableCell In e.Item.Cells
                    currentCell.Attributes.Add("class", "dkpdnn_GridAltItem" + grdItems.Columns(e.Item.Cells.GetCellIndex(currentCell)).FooterText)
                Next

            ElseIf (e.Item.ItemType.Equals(ListItemType.Footer)) Then

                e.Item.Visible = False

            End If

        End Sub

        Private Sub SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlPageSize.SelectedIndexChanged

            If (sender.Equals(ddlPageSize)) Then

                vsPageSize = ddlPageSize.SelectedValue
                ManagePageState(PageState.View)

            End If

        End Sub

        Private Sub SortCommand(ByVal sender As Object, ByVal e As DataGridSortCommandEventArgs) Handles grdItems.SortCommand

            If (vsSortExpression = e.SortExpression) Then
                If (vsSortDirection = "ASC") Then
                    vsSortDirection = "DESC"
                ElseIf (vsSortDirection = "DESC") Then
                    vsSortDirection = "ASC"
                End If
            Else
                vsSortExpression = e.SortExpression
                vsSortDirection = "ASC"
            End If

            ManagePageState(PageState.View)

        End Sub

        Private Sub Click(ByVal sender As Object, ByVal e As EventArgs) Handles lnkFirstPage.Click, lnkPreviousPage.Click, _
            lnkNextPage.Click, lnkLastPage.Click, lnkAdd.Click, lnkUpdate.Click, lnkDelete.Click, lnkSubmit.Click, lnkCancel.Click

            Dim tss_DKP As New tss_DataController

            lblWarning.Text = Null.NullString

            If (sender.Equals(lnkFirstPage)) Then

                vsCurrentPage = 1
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkPreviousPage)) Then

                vsCurrentPage = CInt(vsCurrentPage) - 1
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkNextPage)) Then

                vsCurrentPage = CInt(vsCurrentPage) + 1
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkLastPage)) Then

                vsCurrentPage = vsTotalPages
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkAdd)) Then

                ManagePageState(PageState.Add)

            ElseIf (sender.Equals(lnkUpdate)) Then

                Dim boolIsChecked As Boolean = False

                For Each currentItem As DataGridItem In grdItems.Items

                    If (currentItem.ItemType.Equals(ListItemType.Item)) Or (currentItem.ItemType.Equals(ListItemType.AlternatingItem)) Then

                        Dim chkItem As CheckBox = currentItem.FindControl("chkItem")
                        Dim lblItemID As Label = currentItem.FindControl("lblItemID")

                        If (chkItem.Checked) And (boolIsChecked) Then

                            ManagePageState(PageState.MultiUpdate)
                            Exit For

                        ElseIf (chkItem.Checked) And Not (boolIsChecked) Then

                            boolIsChecked = True

                            ManagePageState(PageState.SingleUpdate)

                            Dim objExistingItem As tss_ItemInfo = tss_DKP.tss_GetItem(CInt(lblItemID.Text))

                            If (objExistingItem Is Nothing) Then
                                ManagePageState(PageState.View)
                                lblWarning.Text = "Error: Item in selection not found."
                                Exit For
                            Else
                                txtItemName.Text = objExistingItem.ItemName
                                txtItemValue.Text = objExistingItem.ItemValue
                                txtItemPercent.Text = objExistingItem.ItemPercent
                                txtItemWowHeadID.Text = objExistingItem.ItemWowHeadID
                            End If

                        End If

                    End If

                Next

                If Not (boolIsChecked) Then
                    ManagePageState(PageState.View)
                End If

            ElseIf (sender.Equals(lnkDelete)) Then

                For Each currentItem As DataGridItem In grdItems.Items

                    If (currentItem.ItemType.Equals(ListItemType.Item)) Or (currentItem.ItemType.Equals(ListItemType.AlternatingItem)) Then

                        Dim chkItem As CheckBox = currentItem.FindControl("chkItem")
                        Dim lblItemID As Label = currentItem.FindControl("lblItemID")

                        If (chkItem.Checked) Then
                            tss_DKP.tss_DeleteItem(CInt(lblItemID.Text))
                        End If

                    End If

                Next

                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkSubmit)) Then

                If (vsPageState = PageState.Add) Then

                    If (txtItemName.Text.Trim.Length = 0) Then
                        lblWarning.Text = "Error: Item name can not be empty."
                    ElseIf (txtItemValue.Text.Trim.Length = 0) Then
                        lblWarning.Text = "Error: Item value can not be empty."
                    ElseIf (txtItemPercent.Text.Trim.Length = 0) Then
                        lblWarning.Text = "Error: Item percent can not be empty."
                    Else

                        Dim objNewItem As New tss_ItemInfo : objNewItem = CBO.InitializeObject(objNewItem, GetType(tss_ItemInfo))

                        objNewItem.ItemName = txtItemName.Text.Trim
                        objNewItem.ItemValue = txtItemValue.Text.Trim
                        objNewItem.ItemPercent = txtItemPercent.Text.Trim
                        objNewItem.ItemWowHeadID = txtItemWowHeadID.Text.Trim
                        objNewItem.BoardID = CInt(Settings("BoardID"))

                        Try
                            tss_DKP.tss_AddItem(objNewItem)
                        Catch ex As ApplicationException
                            lblWarning.Text = "Error: Trying to add item resulted in the following error (" + ex.Message + ")."
                        End Try

                    End If

                    If (lblWarning.Text = Null.NullString) Then
                        ManagePageState(PageState.View)
                    End If

                ElseIf (vsPageState = PageState.SingleUpdate) Then

                    For Each currentItem As DataGridItem In grdItems.Items

                        If (currentItem.ItemType.Equals(ListItemType.Item)) Or (currentItem.ItemType.Equals(ListItemType.AlternatingItem)) Then

                            Dim chkItem As CheckBox = currentItem.FindControl("chkItem")
                            Dim lblItemID As Label = currentItem.FindControl("lblItemID")

                            If (chkItem.Checked) Then

                                Dim objExistingItem As tss_ItemInfo = tss_DKP.tss_GetItem(CInt(lblItemID.Text))

                                If (objExistingItem Is Nothing) Then
                                    lblWarning.Text = "Error: Trying to update item resulted in the following error (Item in selection not found.)."
                                Else

                                    objExistingItem.ItemName = txtItemName.Text.Trim
                                    objExistingItem.ItemValue = txtItemValue.Text.Trim
                                    objExistingItem.ItemPercent = txtItemPercent.Text.Trim
                                    objExistingItem.ItemWowHeadID = txtItemWowHeadID.Text.Trim

                                    Try
                                        tss_DKP.tss_UpdateItem(objExistingItem)
                                    Catch ex As ApplicationException
                                        lblWarning.Text = "Error: Trying to update item resulted in the following error (" + ex.Message + ")."
                                    End Try

                                End If

                            End If

                        End If

                    Next

                    If (lblWarning.Text = Null.NullString) Then
                        ManagePageState(PageState.View)
                    End If

                ElseIf (vsPageState = PageState.MultiUpdate) Then

                    For Each currentItem As DataGridItem In grdItems.Items

                        If (currentItem.ItemType.Equals(ListItemType.Item)) Or (currentItem.ItemType.Equals(ListItemType.AlternatingItem)) Then

                            Dim chkItem As CheckBox = currentItem.FindControl("chkItem")
                            Dim lblItemID As Label = currentItem.FindControl("lblItemID")

                            If (chkItem.Checked) Then

                                Dim objExistingItem As tss_ItemInfo = tss_DKP.tss_GetItem(CInt(lblItemID.Text))

                                If (objExistingItem Is Nothing) Then
                                    lblWarning.Text = lblWarning.Text + IIf(lblWarning.Text.Length > 0, "<br>", "") _
                                        + "Error: Trying to update item resulted in the following error (Item in selection not found.)."
                                Else

                                    objExistingItem.ItemValue = txtItemValue.Text.Trim
                                    objExistingItem.ItemPercent = txtItemPercent.Text.Trim

                                    Try
                                        tss_DKP.tss_UpdateItem(objExistingItem)
                                    Catch ex As ApplicationException
                                        lblWarning.Text = lblWarning.Text + IIf(lblWarning.Text.Length > 0, "<br>", "") _
                                            + "Error: Trying to update item (" + objExistingItem.ItemName _
                                            + ") resulted in the following error (" + ex.Message + ")."
                                    End Try

                                End If

                            End If

                        End If

                    Next

                    BindPage()

                    If (lblWarning.Text = Null.NullString) Then
                        ManagePageState(PageState.View)
                    End If

                End If

            ElseIf (sender.Equals(lnkCancel)) Then

                ManagePageState(PageState.View)

            End If

        End Sub

#End Region

#Region "Public Methods"

        Public Sub Initialize()

            ManagePageState(PageState.View)

        End Sub

#End Region

    End Class

End Namespace
